package com.i8office.android.zhihuixinwu.ui;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.cyan.tools.annotation.ActivityFragmentInject;
import com.cyan.tools.base.BaseFragment;
import com.i8office.android.zhihuixinwu.R;
import com.i8office.android.zhihuixinwu.bean.Preview;
import com.i8office.android.zhihuixinwu.config.Constants;
import com.i8office.android.zhihuixinwu.module.contract.PreviewContract;
import com.i8office.android.zhihuixinwu.module.presenter.PreviewPresenter;

import application.AppApplication;
import butterknife.BindView;
import butterknife.ButterKnife;
import fr.castorflex.android.verticalviewpager.VerticalViewPager;
import view.ThreePointLoadingView;

/**
 * Created by pc on 2018/7/7.
 */
@ActivityFragmentInject(
        contentViewId = R.layout.fragment_attachment
)
public class AttachmentFragment extends BaseFragment<PreviewContract.Presenter> implements PreviewContract.View {
    @BindView(R.id.loading)
    ThreePointLoadingView loading;
    @BindView(R.id.hint)
    TextView hint;
    @BindView(R.id.viewpager)
    VerticalViewPager viewpager;
    private boolean isFragmentVisible = false;
    private boolean isReuseView;
    private boolean isFirstVisible = true;
    private boolean isError;
    private String fileName = "";
    private String pdfUrl = "";
    //PDF
    @BindView(R.id.content)
    FrameLayout content;
    WebView webView;
    private boolean isChangeScale = false;

    @Override
    protected void initView(View rootView) {
        ButterKnife.bind(this, rootView);
        fileName = getArguments().getString("fileName", "");
        mPresenter = new PreviewPresenter(this);
    }

    @Override
    public void showPreview(final Preview preview) {
        isError = false;
        hint.setVisibility(View.GONE);
        if (fileName.endsWith(".ceb")) {
            content.setVisibility(View.VISIBLE);
            initWebView();
            pdfUrl = Constants.BASE_URL + "/Apps/Tiger/Running/ShowCebResult?id=" + preview.getPreviewID();
            preView(pdfUrl);
        } else {
            viewpager.setVisibility(View.VISIBLE);
            final int pageCount = TextUtils.isEmpty(preview.getPageCount()) ? 0 : Integer.parseInt(preview.getPageCount());
            viewpager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
                @Override
                public Fragment getItem(int position) {
                    Fragment fragment = new AttachmentPageFragment();
                    Bundle bundle = new Bundle();
                    String imgUrl = Constants.BASE_URL + "/Apps/Workflow/Running/ShowPreview/" + preview.getPreviewID() + "?page=" + position + "&__session__=" + AppApplication.getSession();
                    bundle.putString("imgUrl", imgUrl);
                    fragment.setArguments(bundle);
                    return fragment;
                }

                @Override
                public int getCount() {
                    return pageCount;
                }
            });
            loading.stop();
        }
    }

    @Override
    public void showMessage(String message) {
        loading.stop();
        isError = false;
        hint.setText(message);
        hint.setVisibility(View.VISIBLE);
    }

    @Override
    public void showError() {
        loading.stop();
        hint.setText("服务器异常");
        hint.setVisibility(View.VISIBLE);
        isError = true;
        hint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isError) mPresenter.getPreview(getArguments().getString("id"), fileName);
            }
        });
    }

    @Override
    public void waitResult() {
        //附件正在处理重发
        mPresenter.getPreview(getArguments().getString("id"), fileName);
    }

    @Override
    public void showProgress() {
        hint.setVisibility(View.GONE);
    }

    @Override
    public void hideProgress() {
    }

    //setUserVisibleHint()在Fragment创建时会先被调用一次，传入isVisibleToUser = false
    //如果当前Fragment可见，那么setUserVisibleHint()会再次被调用一次，传入isVisibleToUser = true
    //如果Fragment从可见->不可见，那么setUserVisibleHint()也会被调用，传入isVisibleToUser = false
    //总结：setUserVisibleHint()除了Fragment的可见状态发生变化时会被回调外，在new Fragment()时也会被回调
    //如果我们需要在 Fragment 可见与不可见时干点事，用这个的话就会有多余的回调了，那么就需要重新封装一个
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        //setUserVisibleHint()有可能在fragment的生命周期外被调用
        if (rootView == null) {
            return;
        }
        if (isFirstVisible && isVisibleToUser) {
            onFragmentFirstVisible();
            isFirstVisible = false;
        }
        if (isVisibleToUser) {
            onFragmentVisibleChange(true);
            isFragmentVisible = true;
            return;
        }
        if (isFragmentVisible) {
            isFragmentVisible = false;
            onFragmentVisibleChange(false);
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initVariable();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getUserVisibleHint()) {
            if (isFirstVisible) {
                onFragmentFirstVisible();
                isFirstVisible = false;
            }
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        initVariable();
    }

    private void initVariable() {
        isFirstVisible = true;
        isFragmentVisible = false;
        rootView = null;
        isReuseView = true;
//        if (resend != null) {
//            handler.removeCallbacks(resend);
//        }
//        resend = null;
//        handler = null;
    }

    /**
     * 设置是否使用 view 的复用，默认开启
     * view 的复用是指，ViewPager 在销毁和重建 Fragment 时会不断调用 onCreateView() -> onDestroyView()
     * 之间的生命函数，这样可能会出现重复创建 view 的情况，导致界面上显示多个相同的 Fragment
     * view 的复用其实就是指保存第一次创建的 view，后面再 onCreateView() 时直接返回第一次创建的 view
     *
     * @param isReuse
     */
    protected void reuseView(boolean isReuse) {
        isReuseView = isReuse;
    }

    public void initWebView() {
        if (content.getChildCount() > 0)
            content.removeAllViews();
        webView = new WebView(getContext());
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setAllowFileAccess(true);
        settings.setAllowFileAccessFromFileURLs(true);
        settings.setAllowUniversalAccessFromFileURLs(true);
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        settings.setDisplayZoomControls(false);

        settings.setUseWideViewPort(true);

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                loading.stop();
            }

            @Override
            public void onScaleChanged(WebView view, float oldScale, float newScale) {
                super.onScaleChanged(view, oldScale, newScale);
                isChangeScale = true;
            }
        });
        content.addView(webView, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));


    }

    /**
     * 去除setUserVisibleHint()多余的回调场景，保证只有当fragment可见状态发生变化时才回调
     * 回调时机在view创建完后，所以支持ui操作，解决在setUserVisibleHint()里进行ui操作有可能报null异常的问题
     * <p>
     * 可在该回调方法里进行一些ui显示与隐藏，比如加载框的显示和隐藏
     *
     * @param isVisible true  不可见 -> 可见
     *                  false 可见  -> 不可见
     */
    protected void onFragmentVisibleChange(boolean isVisible) {
        if (isVisible && isChangeScale&&!TextUtils.isEmpty(pdfUrl)) {
            isChangeScale = false;
            initWebView();
            preView(pdfUrl);
            return;
        }
        if(isVisible&&TextUtils.isEmpty(pdfUrl)){

        }

    }

    /**
     * 预览pdf
     *
     * @param pdfUrl url或者本地文件路径
     */
    private void preView(String pdfUrl) {
        //1.只使用pdf.js渲染功能，自定义预览UI界面
//        webView.loadUrl("file:///android_asset/pdfjs/web/viewer.html?" + pdfUrl);
        webView.loadUrl("file:///android_asset/index.html?" + pdfUrl);
        //2.使用mozilla官方demo加载在线pdf
//        mWebView.loadUrl("http://mozilla.github.io/pdf.js/web/viewer.html?file=" + pdfUrl);
        //3.pdf.js放到本地
//        mWebView.loadUrl("file:///android_asset/pdfjs/web/viewer.html?file=" + pdfUrl);
        //4.使用谷歌文档服务
//        mWebView.loadUrl("http://docs.google.com/gviewembedded=true&url=" + pdfUrl);
    }

    /**
     * 在fragment首次可见时回调，可在这里进行加载数据，保证只在第一次打开Fragment时才会加载数据，
     * 这样就可以防止每次进入都重复加载数据
     * 该方法会在 onFragmentVisibleChange() 之前调用，所以第一次打开时，可以用一个全局变量表示数据下载状态，
     * 然后在该方法内将状态设置为下载状态，接着去执行下载的任务
     * 最后在 onFragmentVisibleChange() 里根据数据下载状态来控制下载进度ui控件的显示与隐藏
     */
    protected void onFragmentFirstVisible() {
        loading.play();
        mPresenter.getPreview(getArguments().getString("id"), fileName);
    }

    protected boolean isFragmentVisible() {
        return isFragmentVisible;
    }
}
